package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entity.*;
import cn.tedu.csmall.product.pojo.param.BrandAddNewParam;
import cn.tedu.csmall.product.pojo.param.BrandUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.*;
import cn.tedu.csmall.product.service.IBrandService;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
public class BrandServiceImpl implements IBrandService {


    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private BrandCategoryMapper brandCategoryMapper;

    @Override
    public void setEnable(Long id) {
        updateEnableById(id, 1);

    }

    private void updateEnableById(Long id,Integer enable) {
        log.debug("开始处理【{}品牌】的业务，ID：{}，目标状态：{}", ENABLE_TEXT[enable], id, enable);
        // 检查数据是否存在
        BrandStandardVO queryResult = brandMapper.getStandardById(id);
        if (queryResult == null) {
            String message = ENABLE_TEXT[enable] + "品牌失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查当前状态是否与参数表示的状态相同
        if (queryResult.getEnable().equals(enable)) {
            String message = ENABLE_TEXT[enable] + "品牌失败，当前品牌已经处于" + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 准备执行更新
        Brand brand = new Brand();
        brand.setId(id);
        brand.setEnable(enable);
        log.debug("即将修改数据，参数：{}", brand);
        int rows = brandMapper.update(brand);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "品牌失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[查询品牌列表]的业务，页码：{},每页记录数:{}",pageNum,pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<BrandListItemVO> list = brandMapper.list();
        PageInfo<BrandListItemVO> pageInfo = new PageInfo<>(list);
        PageData<BrandListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成,即将返回：{}",pageData);
        return pageData;
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {
        log.debug("开始处理[根据ID品牌详情]的业务，参数:{}",id);
        BrandStandardVO queryResult = brandMapper.getStandardById(id);
        if(queryResult == null){
            String message = "查询相册详情失败，相册数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return queryResult;
    }

    @Override
    public void updateById(Long id, BrandUpdateInfoParam brandUpdateInfoParam) {
        log.debug("开始处理[修改品牌详情]的业务，参数:{}",brandUpdateInfoParam);
        Brand brand= brandMapper.selectById(id);
        log.debug("根据ID={}检查品牌数据是否存在,查询结果:{}",id,brand);
        if (brand == null){
            String message = "修改品牌失败，修改的品牌不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        BeanUtils.copyProperties(brandUpdateInfoParam,brand);
        brand.setId(id);
        brandMapper.updateById(brand);
        log.debug("将新的品牌数据更新到数据库，完成！");
    }

    @Override
    public void delete(Long brandId) {
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",brandId);
        int countById = brandMapper.selectCount(queryWrapper);
        log.debug("根据品牌ID统计匹配的品牌数量，结果:{}",countById);
        if(countById == 0 ){
            String message = "删除品牌失败，品牌数据不存在!";
            log.warn(message);
            throw  new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        //检查是否有Spu关联到了此品牌，如果存在，则抛出异常
        QueryWrapper<Spu> queryWrapper1 = new QueryWrapper<Spu>();
        queryWrapper1.eq("brand_id",brandId);
        int countByAlbumId1 = spuMapper.selectCount(queryWrapper1);
        log.debug("根据品牌ID统计匹配的图片数量，结果:{}",countByAlbumId1);
        if (countByAlbumId1 > 0 ){
            String message = "删除品牌失败，仍有图片关联到此品牌";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }


        //检查是否有品牌与类别关联到了此品牌，如果存在，则抛出异常
        QueryWrapper<BrandCategory> queryWrapper2 = new QueryWrapper<BrandCategory>();
        queryWrapper2.eq("brand_id",brandId);
        int countByAlbumId2 = brandCategoryMapper.selectCount(queryWrapper2);
        log.debug("根据品牌ID统计匹配的图片数量，结果:{}",countByAlbumId2);
        if (countByAlbumId2 > 0 ){
            String message = "删除品牌失败，仍有图片关联到此品牌";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }





        brandMapper.deleteById(brandId);


    }

    @Override
    public void addNew(BrandAddNewParam brandAddNewParam) {
        log.debug("开始处理[添加品牌] 的业务,参数",brandAddNewParam);
        QueryWrapper<Brand> queryWrapper  = new QueryWrapper<>();
        queryWrapper.eq("name",brandAddNewParam.getName());
        int countByName = brandMapper.selectCount(queryWrapper);
        if(countByName >0){
            String message = "添加品牌失败，品牌名称已经被占用！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Brand brand = new Brand();
        BeanUtils.copyProperties(brandAddNewParam,brand);
        brand.setGmtCreate(LocalDateTime.now());
        brand.setGmtModified(LocalDateTime.now());
        brandMapper.insert(brand);
    }
}
